﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TransCompare
{
    enum EncodeType
    {
        gbk,
        jis,
        utf,
        big5,
    }

    public partial class Form1 : Form
    {
        public Form1 () {
            InitializeComponent();
        }
        private void Form1_Load (object sender, EventArgs e) {
            InitCombox(SrcEncodeComb);
            InitCombox(DestEncodeComb);
            ReplaceBox.Text = " ";
        }
        private void InitCombox (ComboBox comb) {
            foreach (string name in Enum.GetNames(typeof(EncodeType))) comb.Items.Add(name);
        }
        private Encoding GetEncode (ComboBox comb) {
            Encoding encode = null;
            if (comb.SelectedIndex < 0) return encode;
            EncodeType type = (EncodeType)Enum.Parse(typeof(EncodeType), (string)comb.SelectedItem);
            switch (type) {
                case EncodeType.gbk: encode = Encoding.GetEncoding("GBK");          break;
                case EncodeType.jis: encode = Encoding.GetEncoding("Shift-Jis");    break;
                case EncodeType.utf: encode = Encoding.UTF8;                        break;
                case EncodeType.big5:encode = Encoding.GetEncoding("Big5");         break;
            }
            return encode;
        }
        private void ConvertBtn_Click (object sender, EventArgs e) {
            Encoding src = GetEncode(SrcEncodeComb);
            Encoding dest = GetEncode(DestEncodeComb);
            if (src == null || dest == null) MessageBox.Show("请选择编码！");
            else {
                ConvtDir(DirPathEdit.Text, "*", src, dest, ReplaceBox.Text);
                MessageBox.Show("转换完成！");
            }
        }

        private void SelectDirBtn_Click (object sender, EventArgs e) {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.ShowNewFolderButton = true;
            fd.RootFolder = Environment.SpecialFolder.Desktop;
            if (fd.ShowDialog() == DialogResult.OK) {
                DirPathEdit.Text = fd.SelectedPath;
            }
        }

        void ConvtDir (string path, string pattens, Encoding src, Encoding dest, string replace) {
            foreach (string dir in Directory.GetDirectories(path)) {
                ConvtDir(dir, pattens, src, dest, replace);
            }
            string[] ps = pattens.Split('|');
            foreach (string patten in ps) {
                foreach (string file in Directory.GetFiles(path, patten)) {
                    if (GetType(file) == dest)
                        continue;
                    string[] line = File.ReadAllLines(file, src);
                    int count = line.Length;

                    int comm;
                    string code, comment;
                    for (int i = 0; i < count; i++) {
                        comm = line[i].IndexOf("//");
                        if (comm > 0) {
                            code = line[i].Substring(0, comm);
                            comment = line[i].Substring(comm);
                            if (!string.IsNullOrEmpty(replace)) code = code.Replace("　", replace);
                            line[i] = code + comment;
                        } else if (comm < 0) {
                            if (!string.IsNullOrEmpty(replace)) line[i] = line[i].Replace("　", replace);
                        }
                    }
                    File.WriteAllLines(file, line, dest);
                }
            }
        }

        /// <summary> 
        /// 通过给定的文件流，判断文件的编码类型 
        /// </summary> 
        /// <param name=“fs“>文件流</param> 
        /// <returns>文件的编码类型</returns> 
        public static System.Text.Encoding GetType(string path)
        {
            byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
            byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
            byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF };   //带BOM 
            Encoding enc = Encoding.Default;

            byte[] ss = File.ReadAllBytes(path);

            if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
                enc = Encoding.UTF8;
            else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
                enc = Encoding.BigEndianUnicode;
            else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
                enc = Encoding.Unicode;
            else
                enc = Encoding.Default;
            return enc;
        }

        /// <summary> 
        /// 判断是否是不带 BOM 的 UTF8 格式 
        /// </summary> 
        /// <param name=“data“></param> 
        /// <returns></returns> 
        private static bool IsUTF8Bytes(byte[] data)
        {
            int charByteCounter = 1; //计算当前正分析的字符应还有的字节数 
            byte curByte; //当前分析的字节. 
            for (int i = 0; i < data.Length; i++)
            {
                curByte = data[i];
                if (charByteCounter == 1)
                {
                    if (curByte >= 0x80)
                    {
                        //判断当前 
                        while (((curByte <<= 1) & 0x80) != 0)
                        {
                            charByteCounter++;
                        }
                        //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X 
                        if (charByteCounter == 1 || charByteCounter > 6)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    //若是UTF-8 此时第一位必须为1 
                    if ((curByte & 0xC0) != 0x80)
                    {
                        return false;
                    }
                    charByteCounter--;
                }
            }
            if (charByteCounter > 1)
            {
                throw new Exception("非预期的byte格式");
            }
            return true;
        }

    }
}
